package com.gable.exhibition.service.impl;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.*;
import com.gable.exhibition.model.*;
import com.gable.exhibition.service.ContractActualSendService;
import com.gable.exhibition.service.SequenceService;
import com.gable.exhibition.thread.ChatGroupThread;
import com.gable.exhibition.thread.DispatchEngineerSmsThread;
import com.gable.exhibition.thread.EstimateSendDispatchSmsThread;
import com.gable.exhibition.thread.EstimateSendSmsThread;
import com.gable.exhibition.util.ExceptionUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mj on 2018/2/9.
 */
@Service
public class ContractActualSendServiceImpl implements ContractActualSendService {

    @Value("${serviceSendNoInstall}")
    String serviceSendNoInstall; //发货不需要安装推送给医院短信URL

    @Value("${sendByDoctor}")
    String sendByDoctor;        //发货需要安装推送给医院短信URL

    @Value("${serviceSendByEngineer}")
    String serviceSendByEngineer;   //发货指派工程师推送给工程师短信URL

    @Value("${sendAssignService}")
    String sendAssignService;       // 发货指派给其他服务商

    @Value("${webSocket_InsertSendUrl}")
    String webSocket_InsertSendUrl; //发货流程创建群组

    @Autowired
    ContractActualSendDao contractActualSendDao;

    @Autowired
    ContractDao contractDao;

    @Autowired
    ContractDeviceEstimateSendDao contractDeviceEstimateSendDao;

    @Autowired
    ContractDeviceDao contractDeviceDao;

    @Autowired
    ContractDeviceActualSendDao contractDeviceActualSendDao;

    @Autowired
    InstallDao installDao;

    @Autowired
    UserDao userDao;

    @Autowired
    ContractEstimateSendDao contractEstimateSendDao;

    @Autowired
    SequenceService sequenceService;

    @Autowired
    EventDao eventDao;

    @Autowired
    SupplierDao supplierDao;

    @Autowired
    MaintainerDao maintainerDao;

    @Autowired
    AppointDao appointDao;
    @Override
    public ReturnResultUtil actualSendList(ParameterView parameterView) {
        Map<String,Object> map = new HashMap<String,Object>();
        Long manufacturerId = parameterView.getManufacturerId();
        //厂商登录，查询其下的厂商供应商，获取发货列表
        if(manufacturerId != null){
            Supplier supplier = supplierDao.queryManufacturerSupplier(manufacturerId);
            if(supplier != null)
                parameterView.setSupplierId(supplier.getSupplierId());
        }
        Integer count = contractActualSendDao.actualSendListCount(parameterView);
        if(count > 0){
            List<ContractView> contractViews = contractActualSendDao.actualSendList(parameterView);
            for(ContractView contractView: contractViews){
                Long contractActualSendId = contractView.getContractActualSendId();
                parameterView.setContractActualSendId(contractActualSendId);
                List<ModelView> modelViews = contractActualSendDao.actualSendModelList(parameterView);
                contractView.setModelList(modelViews);
            }
            map.put("data",contractViews);
        }
        map.put("count",count);
        return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,map);
    }

    @Override
    public ReturnResultUtil actualSendInfo(ParameterView parameterView) {
        ContractView contractView = contractActualSendDao.actualSendInfo(parameterView);
        InstallView projectChargePerson = installDao.getProjectChargePerson(parameterView);
        if(projectChargePerson != null){
            contractView.setProjectChargePerson(projectChargePerson.getProjectChargePerson());
            contractView.setProjectChargePersonPhone(projectChargePerson.getProjectChargePersonPhone());
            contractView.setEstimateInstallDate(projectChargePerson.getEstimateInstallDate());
            contractView.setRemark(projectChargePerson.getDispatchRemark());
        }
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,contractView);
    }

    @Override
    @Transactional
    public synchronized ReturnResultUtil sendForActual(SendParameterView sendParameterView) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Long contractId = sendParameterView.getContractId();    //合同ID
        String sendDate = sendParameterView.getSendDate();      //发货日期
        String sendNo = sendParameterView.getSendNo();  //发货单号
        String sendDeviceJson = sendParameterView.getSendDeviceJson();  //发货设备
        String projectChargePerson = sendParameterView.getProjectChargePerson();//工程师名称
        String projectChargePersonPhone = sendParameterView.getProjectChargePersonPhone();//工程师电话
        String estimateInstallDate = sendParameterView.getEstimateInstallDate();//预计安装时间
        Integer oneself = sendParameterView.getOneself();       //是否自身派工


        Long contractActualSendId = UUIDGenerator.getUniqueLong();    //实际发货单主键ID
        //实际发货单信息
        ContractActualSend contractActualSend = new ContractActualSend();
        //选择服务商类型 1102厂商 1103维修商
        Maintainer maintainer = null;
        Long serviceType = sendParameterView.getServiceType();

        //指派记录
        Appoint appoint = new Appoint();
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        appoint.setKeyId(contractActualSendId);
        appoint.setKeyType(2903L);  //发货安装
        Long manufacturerId = sendParameterView.getManufacturerId();
        Long supplierId = sendParameterView.getSupplierId();
        if(manufacturerId != null){
            appoint.setInstructId(manufacturerId);
            appoint.setInstructType(1102L);
        }else if(supplierId != null){
            appoint.setInstructId(supplierId);
            appoint.setInstructType(1105L);
        }
        appoint.setCreatePerson(sendParameterView.getUserId());
        appoint.setInstructedType(serviceType);
        appoint.setInstructedId(sendParameterView.getServiceId());
        appoint.setEngineerName(projectChargePerson);
        appoint.setEngineerPhone(projectChargePersonPhone);

        if(oneself == 0){
            if(serviceType.intValue() == 1103){
                String serviceName = sendParameterView.getServiceName();
                Maintainer maintainerParameter = new Maintainer();
                maintainerParameter.setMaintainerName(serviceName);
                maintainer = maintainerDao.checkMaintainer(maintainerParameter);
                if(maintainer == null){
                    maintainer = new Maintainer();
                    maintainer.setMaintainerId(UUIDGenerator.getUniqueLong());
                    maintainer.setMaintainerName(serviceName);
                    maintainer.setRemark("发货创建维修商");
                    maintainer.setMaintainerContacts(sendParameterView.getMaintainerContacts());
                    maintainer.setMaintainerPhone(sendParameterView.getMaintainerPhone());
                    maintainer.setCreatePerson(sendParameterView.getUserId());
                    maintainer.setIsDel(1); //流程创建线下维修商
                    int i = maintainerDao.insertSelective(maintainer);
                    if(i == 0)
                        return new ReturnResultUtil(500,MessageUtil.MAINTAINERCREATEERROR);
                }
                User userParameter = new User();
                userParameter.setMobile(projectChargePersonPhone);
                userParameter.setUserName(projectChargePersonPhone);
                User user = userDao.checkUserByEngineerPhone(userParameter);
                if(user == null){
                    user = new User();
                    user.setMaintainerId(maintainer.getMaintainerId());
                    user.setUserId(UUIDGenerator.getUniqueLong());
                    user.setUserName(projectChargePersonPhone);
                    user.setMobile(projectChargePersonPhone);
                    user.setRealName(projectChargePerson);
                    user.setType(serviceType);    //1102厂商 1103维修商 1105供应商
                    user.setTag(1006L); //维修商工程师
                    user.setRemark("安装派工产生用户");
                    int row5 = userDao.insertSelective(user);
                    if(row5 == 0)
                        throw new ExceptionUtil(500,MessageUtil.USERERROR,user);
                }
                appoint.setInstructedId(maintainer.getMaintainerId());

                //发货单绑定工程师ID
                contractActualSend.setProjectChargePersonId(user.getUserId());
                //发货单绑定服务商ID
                contractActualSend.setServiceId(maintainer.getMaintainerId());
            }
        }else
        //自身指派工程师
        if(oneself == 1){
            User userParameter = new User();
            userParameter.setMobile(projectChargePersonPhone);
            userParameter.setUserName(projectChargePersonPhone);
            User user = userDao.checkUserByEngineerPhone(userParameter);
            if(user == null){
                user = new User();
                Long userTag = 0L;
                if(serviceType.intValue() == 1102){
                    userTag = 1004L;        //厂商工程师
                    user.setManufacturerId(sendParameterView.getServiceId());
                }else if(serviceType.intValue() == 1105){
                    userTag = 1009L;        //供应商工程师
                    user.setSupplierId(sendParameterView.getServiceId());
                }

                user.setUserId(UUIDGenerator.getUniqueLong());
                user.setUserName(projectChargePersonPhone);
                user.setMobile(projectChargePersonPhone);
                user.setRealName(projectChargePerson);
                user.setType(serviceType);    //1102厂商  1105供应商
                user.setTag(userTag);
                user.setRemark("安装派工产生用户");
                int row5 = userDao.insertSelective(user);
                if(row5 == 0)
                    throw new ExceptionUtil(500,MessageUtil.USERERROR,user);
            }
            //发货单绑定工程师ID
            contractActualSend.setProjectChargePersonId(user.getUserId());
            //发货单绑定服务商ID
            contractActualSend.setServiceId(sendParameterView.getServiceId());
        }
        //录入指派记录
        int row = appointDao.insertSelective(appoint);
        if(row == 0)
            throw new ExceptionUtil(500,MessageUtil.APPOINTERROR,appoint);
        //合同信息
        ContractView contract = contractDao.queryContractForSendSms(contractId);
        if(contract == null)
            return new ReturnResultUtil(500,MessageUtil.CONTRACTNOEXIST);
        //1.insert 产生实际发货单
        contractActualSend.setContractActualSendId(contractActualSendId);
        contractActualSend.setContractId(contractId);
        contractActualSend.setSendNo(sendNo);
        contractActualSend.setSendDate(sendDate);
        contractActualSend.setServiceType(serviceType);
        contractActualSend.setCreatePerson(sendParameterView.getUserId());
        int row1 = contractActualSendDao.insertSelective(contractActualSend);
        if(row1 == 0)
            throw new ExceptionUtil(500,MessageUtil.ACTUALINSERT,contractActualSend);

        //实际发货设备
        Integer sendCountForSms = 0;        //统计短信所需的发货数量
        List<ContractDeviceEstimateSend> contractDeviceEstimateSends = JSON.parseArray(sendDeviceJson, ContractDeviceEstimateSend.class);
        for(ContractDeviceEstimateSend contractDeviceEstimateSend : contractDeviceEstimateSends){
            Long contractDeviceId = contractDeviceEstimateSend.getContractDeviceId();       //合同设备ID
            Integer actualSendQuantity = contractDeviceEstimateSend.getActualQuantity();    //这次的发货数量
            sendCountForSms += actualSendQuantity;
            if(actualSendQuantity <= 0)
                throw new ExceptionUtil(500,MessageUtil.SENDCOUNT);
            ContractDevice contractDevice = contractDeviceDao.selectByPrimaryKey(contractDeviceId);     //合同设备信息
            //发货数量 + 历史发货数量 不能大于采购数量
//            if(actualSendQuantity + contractDevice.getActualQuantity() > contractDevice.getQuantity())
//                throw new ExceptionUtil(500,MessageUtil.ACTUALQUANTITYERROR,contractDevice);
            //1-1.产生实际发货设备
            ContractDeviceActualSend contractDeviceActualSend = new ContractDeviceActualSend();
            contractDeviceActualSend.setContractDeviceActualSendId(UUIDGenerator.getUniqueLong());
            contractDeviceActualSend.setContractActualSendId(contractActualSendId);
            contractDeviceActualSend.setContractDeviceId(contractDeviceId);
            contractDeviceActualSend.setActualSendQuantity(contractDeviceEstimateSend.getActualQuantity());
            contractDeviceActualSend.setActualSendDate(sendDate);
            contractDeviceActualSend.setRemark(contractDeviceEstimateSend.getRemark());
            int row1_1 = contractDeviceActualSendDao.insertSelective(contractDeviceActualSend);
            if(row1_1 == 0)
                throw new ExceptionUtil(500,MessageUtil.DEVICEACTUALSEND,contractDeviceActualSend);
            //2.根据合同设备ID查询预计发货信息
            //单纯根据合同设备ID查询 有可能会查询多条预计发货单 （一个合同设备对应多次预计发货）
            ContractDeviceEstimateSend para = new ContractDeviceEstimateSend();
            para.setContractDeviceId(contractDeviceId);
            List<ContractDeviceEstimateSendView> contractDeviceEstimateSendViews = contractDeviceEstimateSendDao.selectContractDeviceEstimateSend(para);
            //3.将发货数量逐个添加到每条预计发货数量上，实际发货数量已经和预计发货数量持平，就填充到下条发货单的实际发货数量上
            //若下条发货单数量也持平，则填充到最后一条实际发货数量上
            int size = contractDeviceEstimateSendViews.size();
            //如果该合同设备没有发货单，产生一条虚拟发货单
            if(size == 0){
                //虚拟发货单
                ContractEstimateSend contractEstimateSend = new ContractEstimateSend();
                contractEstimateSend.setContractEstimateSendId(UUIDGenerator.getUniqueLong());
                contractEstimateSend.setContractId(contractId);
                contractEstimateSend.setRemark("虚拟发货单");
                contractEstimateSend.setCreatePerson(sendParameterView.getUserId());
                row = contractEstimateSendDao.insertSelective(contractEstimateSend);
                if(row == 0)
                    throw new ExceptionUtil(500,MessageUtil.FICTITIOUSESTIMATESEND,contractEstimateSend);
                //虚拟发货设备
                ContractDeviceEstimateSend cdes = new ContractDeviceEstimateSend();
                cdes.setContractDeviceEstimateSendId(UUIDGenerator.getUniqueLong());
                cdes.setContractEstimateSendId(contractEstimateSend.getContractEstimateSendId());
                cdes.setContractDeviceId(contractDeviceId);
                cdes.setEstimateQuantity(0);
                cdes.setActualQuantity(0);
                cdes.setRemark("虚拟发货单下产生的虚拟发货设备");
                row = contractDeviceEstimateSendDao.insertSelective(cdes);
                if(row == 0)
                    throw new ExceptionUtil(500,MessageUtil.FICTITIOUSDEVICEESTIMATESEND,contractEstimateSend);
                contractDeviceEstimateSendViews = contractDeviceEstimateSendDao.selectContractDeviceEstimateSend(para);
                size = contractDeviceEstimateSendViews.size();
            }
            for(int i = 0; i < size; i++){
                ContractDeviceEstimateSendView contractDeviceEstimateSendView = contractDeviceEstimateSendViews.get(i);
                Integer estimateQuantity = contractDeviceEstimateSendView.getEstimateQuantity();    //预计发货数量
                Integer actualQuantity = contractDeviceEstimateSendView.getActualQuantity();    //历史实际发货数量
                Integer installCount = 0; //派工数量,也是这次平摊数量
                if(actualSendQuantity > 0){
                    //最后一条发货单
                    if(i+1 == size){
                        contractDeviceEstimateSendView.setActualQuantity(actualQuantity + actualSendQuantity);
                        installCount = actualSendQuantity;
                    }else{
                        if(actualSendQuantity + actualQuantity >= estimateQuantity){
                            installCount = estimateQuantity - actualQuantity; //派工数量,也是这次平摊数量
                            contractDeviceEstimateSendView.setActualQuantity(estimateQuantity);
                        }else{
                            installCount = actualSendQuantity; //派工数量,也是这次平摊数量
                            contractDeviceEstimateSendView.setActualQuantity(actualSendQuantity + actualQuantity);
                        }
                    }
                    actualSendQuantity = actualSendQuantity - installCount;   //剩余平摊数量

                    //回写预计发货单的实际发货数量
                    int row3 = contractDeviceEstimateSendDao.updateBySend(contractDeviceEstimateSendView);
                    if(row3 == 0)
                        throw new ExceptionUtil(500,MessageUtil.UPDATEACTUALQUANTITY,contractDeviceEstimateSendView);
                    //4. 回写合同设备实际发货数量
                    contractDevice.setActualQuantity(contractDevice.getActualQuantity()+installCount);
                    int row4 = contractDeviceDao.updateByPrimaryKeySelective(contractDevice);
                    if(row4 == 0)
                        throw new ExceptionUtil(500,MessageUtil.UPDATECONTRACTACTUALQUANTITY,contractDevice);


                    //5. 根据是否安装 产生安装派工 0false 1true
                    Integer whetherNeedInstall = contractDevice.getWhetherNeedInstall();
                    //产生安装派工
                    //派工数量产生派工
                    if(oneself == 1 || serviceType.intValue() == 1103){
                        for(int j = 0; j < installCount; j++){
                            Event event = new Event();
                            Install install = new Install();
                            install.setInstallId(UUIDGenerator.getUniqueLong());
                            install.setContractDeviceActualSendId(contractDeviceActualSend.getContractDeviceActualSendId());
                            install.setHospitalId(contract.getFirstParty());
                            install.setHospitalContacts(sendParameterView.getHospitalContacts());
                            install.setHospitalPhone(sendParameterView.getHospitalPhone());
                            install.setStatus(1202L);
                            install.setIsFictitious(1); //默认为虚拟安装单
                            install.setServiceType(serviceType);    //1102厂商 1103维修商 1105供应商
                            install.setServiceId(contractActualSend.getServiceId());


                            event.setEventTitle("设备发货等待验收");
                            event.setEventContent("设备:"+contractDevice.getDeviceName()+"于"+sendDate+"发货，等待验收");
                            event.setType(2403L);   //设备发货等待安装	设备事件类型

                            if(whetherNeedInstall == 1) {   //需要安装
                                install.setProjectChargePerson(projectChargePerson);
                                install.setProjectChargePersonPhone(projectChargePersonPhone);
                                install.setEstimateInstallDate(estimateInstallDate);
                                install.setStatus(1201L);//当需要安装时状态为待安装
                                install.setIsFictitious(0); //实际安装单
                                install.setDispatchRemark(sendParameterView.getRemark());
                                Long aLong = sequenceService.querySequence();
                                String installNo = sdf.format(new Date())+aLong;
                                install.setInstallNo(installNo);
                                event.setEventTitle("设备发货等待安装");
                                event.setEventContent("设备:"+contractDevice.getDeviceName()+"于"+sendDate+"发货，等待安装");
                                event.setType(2400L);   //设备发货等待安装	设备事件类型
                            }

                            int row5 = installDao.insertSelective(install);
                            if(row5 == 0)
                                throw new ExceptionUtil(500,MessageUtil.INSTALLERROR,install);

                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            event.setEventId(UUIDGenerator.getUniqueLong());
                            event.setKeyType(1600L);        //安装
                            event.setKeyId(install.getInstallId());
                            event.setEventDateTime(simpleDateFormat.format(new Date()));
                            event.setCreatePerson(sendParameterView.getUserId());
                            row = eventDao.insertSelective(event);
                            if(row == 0)
                                throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);
                        }
                    }
                }
            }
        }

        new Thread(new ChatGroupThread(contractActualSendId+"",webSocket_InsertSendUrl)).start();

        //1：发货成功，2：医院有一批设备已发货，3：工程师有安装信息
        String hospitalName = contract.getHospitalName();
        String supplierName = contract.getSupplierName();
        String contractNo = contract.getContractNo();
        //sendCountForSms
        List<String> hospitalMobile = contract.getMobileList();
        //指派自身工程师或维修商工程师
        if(oneself == 1 || sendParameterView.getServiceType().intValue() == 1103){
            String serviceName = "";
            if(sendParameterView.getServiceType().intValue() == 1103){
                serviceName = maintainer.getMaintainerName();
            }else{
                serviceName = sendParameterView.getSupplierName();
                if(!StringUtils.isEmpty(sendParameterView.getManufacturerName()))
                    serviceName = sendParameterView.getManufacturerName();
            }
            new Thread(new EstimateSendSmsThread(hospitalName,supplierName,contractNo,
                    sendCountForSms,hospitalMobile,projectChargePersonPhone,serviceName,
                    sendParameterView.getProjectChargePerson(),estimateInstallDate,serviceSendNoInstall,serviceSendByEngineer,sendByDoctor)).start();
        }
        //指派其他服务商
        else{
            new Thread(new EstimateSendDispatchSmsThread(hospitalName,supplierName,contractNo,contractActualSend.getServiceType(),contractActualSend.getServiceId(),userDao,sendAssignService)).start();
        }
        return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
    }

    @Override
    public ReturnResultUtil contractForActual(ParameterView parameterView) {
        Map<String,Object> map = new HashMap<String,Object>();
        Long manufacturerId = parameterView.getManufacturerId();
        //厂商登录，查询其下的厂商供应商，获取发货列表
        if(manufacturerId != null){
            Supplier supplier = supplierDao.queryManufacturerSupplier(manufacturerId);
            if(supplier != null)
                parameterView.setSupplierId(supplier.getSupplierId());
        }
        int count = contractDao.contractForActualCount(parameterView);
        if(count > 0) {
            List<Contract> contracts = contractDao.contractForActual(parameterView);
            map.put("data",contracts);
        }
        map.put("count",count);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,map);
    }

    @Override
    public ReturnResultUtil dispatchForSend(SendParameterView sendParameterView) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        Long serviceType = sendParameterView.getServiceType(); //1102厂商 1103维修商 1105供应商
        Integer oneself = sendParameterView.getOneself();
        Long contractActualSendId = sendParameterView.getContractActualSendId();
        String projectChargePerson = sendParameterView.getProjectChargePerson();
        String projectChargePersonPhone = sendParameterView.getProjectChargePersonPhone();
        String estimateInstallDate = sendParameterView.getEstimateInstallDate();
        ContractActualSend contractActualSend = contractActualSendDao.selectByPrimaryKey(contractActualSendId);
        if(contractActualSend == null)
            return new ReturnResultUtil(500,MessageUtil.CONTRACTESTIMATESENDNOEXIST);

        //指派记录
        Appoint appoint = new Appoint();
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        appoint.setKeyId(contractActualSendId);
        appoint.setKeyType(2903L);  //发货安装
        appoint.setInstructId(sendParameterView.getManufacturerId());
        appoint.setInstructType(1102L);
        appoint.setCreatePerson(sendParameterView.getUserId());
        appoint.setInstructedType(serviceType);
        appoint.setInstructedId(sendParameterView.getServiceId());
        appoint.setCreateTime(format);
        appoint.setEngineerName(projectChargePerson);
        appoint.setEngineerPhone(projectChargePersonPhone);

//        if(oneself == 0 && serviceType.intValue() == 1103){
//            String serviceName = sendParameterView.getServiceName();
//            Maintainer maintainerParameter = new Maintainer();
//            maintainerParameter.setMaintainerName(serviceName);
//            maintainer = maintainerDao.checkMaintainer(maintainerParameter);
//            if(maintainer == null){
//                maintainer = new Maintainer();
//                maintainer.setMaintainerId(UUIDGenerator.getUniqueLong());
//                maintainer.setMaintainerName(serviceName);
//                maintainer.setRemark("厂商发货创建维修商");
//                maintainer.setMaintainerContacts(sendParameterView.getMaintainerContacts());
//                maintainer.setMaintainerPhone(sendParameterView.getMaintainerPhone());
//                maintainer.setCreatePerson(sendParameterView.getUserId());
//                maintainer.setIsDel(1); //流程创建线下维修商
//                int i = maintainerDao.insertSelective(maintainer);
//                if(i == 0)
//                    return new ReturnResultUtil(500,MessageUtil.MAINTAINERCREATEERROR);
//            }
//            User userParameter = new User();
//            userParameter.setMobile(projectChargePersonPhone);
//            userParameter.setUserName(projectChargePersonPhone);
//            User user = userDao.checkUserByEngineerPhone(userParameter);
//            if(user == null){
//                user = new User();
//                user.setMaintainerId(maintainer.getMaintainerId());
//                user.setUserId(UUIDGenerator.getUniqueLong());
//                user.setUserName(projectChargePersonPhone);
//                user.setMobile(projectChargePersonPhone);
//                user.setRealName(projectChargePerson);
//                user.setType(serviceType);    //1102厂商 1103维修商 1105供应商
//                user.setTag(1006L); //维修商工程师
//                user.setRemark("安装派工产生用户");
//                int row5 = userDao.insertSelective(user);
//                if(row5 == 0)
//                    throw new ExceptionUtil(500,MessageUtil.USERERROR,user);
//            }
//            appoint.setInstructedId(maintainer.getMaintainerId());
//            //发货单绑定工程师ID
//            contractActualSend.setProjectChargePersonId(user.getUserId());
//            contractActualSend.setServiceId(maintainer.getMaintainerId());
//        }
//        //指派自身工程师
//        else
        contractActualSend.setServiceId(sendParameterView.getServiceId());
        if(oneself == 1){
            User userParameter = new User();
            userParameter.setMobile(projectChargePersonPhone);
            userParameter.setUserName(projectChargePersonPhone);
            User user = userDao.checkUserByEngineerPhone(userParameter);
            if(user == null){
                user = new User();
                user.setManufacturerId(sendParameterView.getManufacturerId());
                user.setUserId(UUIDGenerator.getUniqueLong());
                user.setUserName(projectChargePersonPhone);
                user.setMobile(projectChargePersonPhone);
                user.setRealName(projectChargePerson);
                user.setType(serviceType);    //1102厂商  1105供应商
                user.setTag(1004L);
                user.setRemark("安装派工产生用户");
                int row5 = userDao.insertSelective(user);
                if(row5 == 0)
                    throw new ExceptionUtil(500,MessageUtil.USERERROR,user);
            }
            //发货单绑定工程师ID
            contractActualSend.setProjectChargePersonId(user.getUserId());
            contractActualSend.setServiceId(sendParameterView.getManufacturerId());
        }

        //回写上条指派记录的响应时间
        AppointView appointView = new AppointView();
        appointView.setKeyId(contractActualSendId);
        Appoint appoint1 = appointDao.queryLastAppoint(appointView);
        if(appoint1 == null)
            throw new ExceptionUtil(500,MessageUtil.APPOINTERROR);
        appoint1.setResponseTime(format);
        int i = appointDao.updateByPrimaryKeySelective(appoint1);
        if(i == 0)
            throw new ExceptionUtil(500,MessageUtil.APPOINTERROR,appoint);

        i = appointDao.insertSelective(appoint);
        if(i == 0)
            throw new ExceptionUtil(500,MessageUtil.APPOINTERROR,appoint);

        contractActualSend.setServiceType(serviceType);
        i = contractActualSendDao.updateByPrimaryKeySelective(contractActualSend);
        if(i == 0)
            throw new ExceptionUtil(500,MessageUtil.UPDATEACTUAL,contractActualSend);

        //根据实际发货单ID查询本次发货设备信息
        List<ContractDeviceActualSendView> contractDeviceActualSends = contractDeviceActualSendDao.queryByContractActualSendId(contractActualSendId);
        Integer sendCountForSms = 0;        //统计短信所需的发货数量
        for(ContractDeviceActualSendView contractDeviceActualSend : contractDeviceActualSends){
            Integer actualSendQuantity = contractDeviceActualSend.getActualSendQuantity();
            sendCountForSms += actualSendQuantity;
            Long contractDeviceActualSendId = contractDeviceActualSend.getContractDeviceActualSendId();
            //查询是否是重新指派工程师
            List<Install> installs = installDao.queryInstalls(contractDeviceActualSendId);
            if(installs != null && installs.size() > 0){
                Install install = installs.get(0);
                install.setHospitalContacts(sendParameterView.getHospitalContacts());
                install.setHospitalPhone(sendParameterView.getHospitalPhone());
                install.setServiceType(serviceType);    //1102厂商 1103维修商
                install.setServiceId(sendParameterView.getServiceId());
//                if(serviceType.intValue() == 1103)
//                    install.setServiceId(maintainer.getMaintainerId());
                if(contractDeviceActualSend.getWhetherNeedInstall() == 1) {   //需要安装
                    install.setProjectChargePerson(projectChargePerson);
                    install.setProjectChargePersonPhone(projectChargePersonPhone);
                    install.setEstimateInstallDate(estimateInstallDate);
                    install.setDispatchRemark(sendParameterView.getDispatchRemark());
                }
                i = installDao.updateEngineer(install);
                if(i == 0)
                    throw new ExceptionUtil(500,MessageUtil.INSTALLERROR,install);
                continue;
            }else{
                if(oneself == 1 || sendParameterView.getServiceType().intValue() == 1103){
                    for(int j = 0;j < actualSendQuantity; j++){
                        Event event = new Event();
                        Install install = new Install();
                        install.setInstallId(UUIDGenerator.getUniqueLong());
                        install.setContractDeviceActualSendId(contractDeviceActualSendId);
                        install.setHospitalId(contractDeviceActualSend.getFirstParty());
                        install.setHospitalContacts(sendParameterView.getHospitalContacts());
                        install.setHospitalPhone(sendParameterView.getHospitalPhone());
                        install.setStatus(1202L);
                        install.setIsFictitious(1); //默认为虚拟安装单
                        install.setServiceType(serviceType);    //1102厂商 1103维修商
                        install.setServiceId(sendParameterView.getServiceId());
//                        if(serviceType.intValue() == 1103)
//                            install.setServiceId(maintainer.getMaintainerId());

                        event.setEventTitle("设备发货等待验收");
                        event.setEventContent("设备:"+contractDeviceActualSend.getDeviceName()+"于"+contractDeviceActualSend.getActualSendDate()+"发货，等待验收");
                        event.setType(2403L);   //设备发货等待安装	设备事件类型

                        if(contractDeviceActualSend.getWhetherNeedInstall() == 1) {   //需要安装
                            install.setProjectChargePerson(projectChargePerson);
                            install.setProjectChargePersonPhone(projectChargePersonPhone);
                            install.setEstimateInstallDate(estimateInstallDate);
                            install.setStatus(1201L);//当需要安装时状态为待安装
                            install.setIsFictitious(0); //实际安装单
                            install.setDispatchRemark(sendParameterView.getDispatchRemark());
                            Long aLong = sequenceService.querySequence();
                            String installNo = sdf.format(new Date())+aLong;
                            install.setInstallNo(installNo);
                            event.setEventTitle("设备发货等待安装");
                            event.setEventContent("设备:"+contractDeviceActualSend.getDeviceName()+"于"+contractDeviceActualSend.getActualSendDate()+"发货，等待安装");
                            event.setType(2400L);   //设备发货等待安装	设备事件类型
                        }
                        int row4 = installDao.insertSelective(install);
                        if(row4 == 0)
                            throw new ExceptionUtil(500,MessageUtil.INSTALLERROR,install);
                        event.setEventId(UUIDGenerator.getUniqueLong());
                        event.setKeyType(1600L);        //安装
                        event.setKeyId(install.getInstallId());
                        event.setEventDateTime(format);
                        event.setCreatePerson(sendParameterView.getUserId());
                        int row = eventDao.insertSelective(event);
                        if(row == 0)
                            throw new ExceptionUtil(500,MessageUtil.INSERTEVENTERROR,event);
                    }
                }
            }
        }

        new Thread(new ChatGroupThread(contractActualSendId+"",webSocket_InsertSendUrl)).start();
        //推送 1：医院收到指派工程师信息，2：工程师有安装信息
        new Thread(new DispatchEngineerSmsThread(sendParameterView.getServiceType(),sendParameterView.getServiceId(),
                sendParameterView.getManufacturerName(),contractActualSendId,estimateInstallDate,projectChargePerson,
                projectChargePersonPhone,sendCountForSms,contractActualSendDao,userDao,sendByDoctor,serviceSendByEngineer,sendAssignService)).start();
        return new ReturnResultUtil(200,MessageUtil.SUCCESSFUL);
    }
}
